<?php
/**
 * DBShop 电子商务系统
 *
 * ==========================================================================
 * @link      https://www.dbshop.net/
 * @copyright 北京珑大钜商科技有限公司，并保留所有权利。
 * @license   https://www.dbshop.net/license.html License
 * ==========================================================================
 *
 * @author    静静的风 <baron@loongdom.cn>
 *
 */

namespace Operation\Repository;

use Doctrine\ORM\EntityRepository;
use Operation\Entity\Coupon;
use Operation\Entity\UserCoupon;
use function Doctrine\ORM\QueryBuilder;

class CouponRepository extends EntityRepository
{
    /**
     * 后台优惠券列表
     * @return int|mixed|string
     */
    public function findCouponList()
    {
        $query = $this->getEntityManager()->createQueryBuilder();
        $query->select('c')
            ->addSelect('(SELECT COUNT(u.userCouponId) FROM '.UserCoupon::class.' AS u WHERE u.couponId=c.couponId) AS userCouponNum')
            ->addSelect('(SELECT COUNT(uc.userCouponId) FROM '.UserCoupon::class.' AS uc WHERE uc.couponId=c.couponId AND uc.usedOrderId > 0) AS usedCouponNum')
            ->from(Coupon::class, 'c')
            ->orderBy('c.couponId', 'DESC');

        return $query->getQuery()->getResult();
    }
    /*=======================================下面为前台使用=======================================*/
    /**
     * 显示可以点击的优惠券，同时显示是否已经领取
     * @param $idArray
     * @param $userId
     * @return int|mixed|string
     */
    public function shopClickCouponList($idArray, $userId)
    {
        $query = $this->getEntityManager()->createQueryBuilder();
        $query->select('c')
            ->addSelect('(SELECT u.userCouponId FROM '.UserCoupon::class.' AS u WHERE u.couponId=c.couponId AND u.userId='.$userId.') AS userCouponId')
            ->from(Coupon::class, 'c')
            ->where($query->expr()->in('c.couponId', $idArray));

        return $query->getQuery()->getResult();
    }
}